package com.dts.server.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dts.server.common.base.BaseController;
import com.dts.server.common.base.BaseQuery;
import com.dts.server.common.base.BaseSession;
import com.dts.server.common.enums.ResultCode;
import com.dts.server.common.result.HttpResult;
import com.dts.server.common.result.ListResult;
import com.dts.server.dbutil.entity.ProjectMonitor;
import com.dts.server.dbutil.entity.Template;
import com.dts.server.service.HistoryTableService;
import com.dts.server.service.ProjectMonitorService;
import com.dts.server.service.TemplateService;

/**
 * @ClassName:  TemplateController 
 * @author 范旭蛟
 * @date 2021年10月25日 下午8:13:26
 * @Description: 模板 Controller
 */
@RestController
@RequestMapping("/template")
public class TemplateController extends BaseController {

	@Resource
	private TemplateService templateService;
	
	@Resource
	private ProjectMonitorService monitorService;
	
	@Resource
	private HistoryTableService tableService;
	
	/**
	 * 查询
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/query")
	public HttpResult<?> query(@Validated BaseQuery param, HttpSession session) throws Exception {
		ListResult<Template> result = templateService.query(param, new BaseSession(session));
		if (result != null) {
			return responseOK(result);
		}
		return responseFail(ResultCode.S_NULL_ERROR);
	}

	/**
	 * 新增模板
	 * @param template
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/add")
	public HttpResult<?> add(Template template, HttpSession session) throws Exception {
		if (templateService.add(template, new BaseSession(session))) {
			return responseOK();
		}
		return responseFail(ResultCode.S_UNKNOWN_ERROR);
	}

	/**
	 * 编辑模板
	 * @param template
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	public HttpResult<?> edit(Template template, HttpSession session) throws Exception {
		if (templateService.edit(template, new BaseSession(session))) {
			return responseOK();
		}
		return responseFail(ResultCode.S_UNKNOWN_ERROR);
	}

	/**
	 * 删除模板
	 * @param id
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public HttpResult<?> delete(Integer id, HttpSession session) throws Exception {
		if (templateService.delete(id, new BaseSession(session))) {
			List<ProjectMonitor> list = monitorService.queryByTemplate(id);
			if(list != null){
				for(ProjectMonitor monitor : list){
					tableService.dropTable(monitor.getId());
				}
			}
			return responseOK();
		}
		return responseFail(ResultCode.S_UNKNOWN_ERROR);
	}
}
